package org.mc.service;

import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.mc.api.es.AccountServiceV1;
import org.mc.bean.Account;
import org.mc.common.data.PagedDTO;
import org.mc.common.data.ResultData;
import org.mc.common.util.BeanUtils;
import org.mc.common.util.JSONUtils;
import org.mc.domainservice.AccountDomainService;
import org.mc.request.es.AccountRequest;
import org.mc.response.es.AccountDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by luoxf on 2018/5/29.
 */
@RestController
@Slf4j
public class AccountRestServiceV1 implements AccountServiceV1 {

    @Autowired
    private AccountDomainService accountDomainService;

    @Override
    public ResultData add(@RequestBody AccountRequest accountRequest) {
        log.info("--------------------------");

        Account account = BeanUtils.convert(accountRequest, Account.class);
        account.setCreateTime(new Date());

        account = accountDomainService.save(account);
        log.info("add:" + JSONUtils.toJson(account));
        return ResultData.ok(account);
    }

    @Override
    public ResultData<AccountDTO> get(Long id) {
        Account account = accountDomainService.getByid(id);
        log.info("get:" + JSONUtils.toJson(account));
        AccountDTO accountDTO = BeanUtils.convert(account, AccountDTO.class);
        return ResultData.ok(accountDTO);
    }

    @Override
    public ResultData<PagedDTO<List<AccountDTO>>> getPage(@ApiParam(value = "这是当前页数")
                                                          @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                                                          @ApiParam(value = "这是每页条数")
                                                          @RequestParam(value = "pageSize", defaultValue = "2") int pageSize) {
        Page page = accountDomainService.listPage(pageIndex, pageSize);
        //log.info("page:" + JSONUtils.toJson(page));

        PagedDTO pagedDTO = new PagedDTO();
        pagedDTO.setCount(page.getTotalPages());
        pagedDTO.setPageIndex(pageIndex);
        pagedDTO.setPageSize(pageSize);

        List<AccountDTO> list = listBeanToDTO(page, AccountDTO.class);


        pagedDTO.setList(list);
        return ResultData.ok(pagedDTO);
    }

    private <T> List<T> listBeanToDTO(Page page, Class<T> obj) {
        return (List<T>) page.getContent().stream().map(rs -> {
            log.info(JSONUtils.toJson(rs));
            return rs;
            //return BeanUtils.convert(rs, obj);
        }).collect(Collectors.toList());
    }
}
